/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.http;

import org.apache.http.Consts;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 简单的GET请求执行器，请求的参数是String, 返回的结果也是String
 * 
 * @author WuBo (wub1@minshenglife.com)
 * 
 */
public class SimpleGetRequestExecutor implements
        RequestExecutor<String, String> {

    private Charset charset = Consts.UTF_8;

    public SimpleGetRequestExecutor(String charset) {
        this.charset = Charset.forName(charset);
    }

    public SimpleGetRequestExecutor() {}

    @Override
    public String execute(CloseableHttpClient httpclient, String uri,
            String queryParam) throws ClientProtocolException, IOException {
        if (queryParam != null) {
            if (uri.indexOf('?') == -1) {
                uri += '?';
            }
            uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
        }
        HttpGet httpGet = new HttpGet(uri);

        CloseableHttpResponse response = httpclient.execute(httpGet);
        String responseContent = CharsetResponseHandler.HANDLERS.get(this.charset).handleResponse(
                response);
        return responseContent;
    }

}
